package com.ubhave.powertracker;

import java.util.Date;

import android.app.Activity;
import android.support.v4.app.FragmentActivity;
//import android.app.DialogFragment;
import android.support.v4.app.DialogFragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.*;

public class DailyGoalUpdateActivity extends FragmentActivity implements LoginDialogListener{
       
	int[] update = {0,0,0,0,0,0,0};
	String[] goal = new String[7];
	int goalcount = 0;
	
	LifeGuideConnector lgc;
	SharedPreferences settings;
	SharedPreferences.Editor editor;
	
	PageSensorLogger psl;
	PageLogger pl;
	
	String usr;
	String intervention;
	int day;
	int week;
	
	ScrollView svmain;
	LinearLayout llmain;
	
	String activityPlan;
	
	/** Called when the activity is first created. */
	@Override
    public void onCreate(Bundle savedInstanceState) {
		
		//StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        //StrictMode.setThreadPolicy(policy);
		
		settings=PreferenceManager.getDefaultSharedPreferences(getBaseContext());
		editor = settings.edit();
		lgc = new LifeGuideConnector(settings);
		activityPlan = settings.getString("PAplan", "");
		
		super.onCreate(savedInstanceState);
		
		        
        String[] startDateString = settings.getString("appStart", "").split("-");
		Date startDate = new Date(new Integer(startDateString[2]),new Integer(startDateString[1]),new Integer(startDateString[0]));
		Date currentDate = new Date();
		long diff = currentDate.getTime()-startDate.getTime();
		double daysDiff = diff/(1000*60*60*24);
		day=1+new Double(Math.floor(daysDiff)).intValue();
		week=new Double(Math.ceil(new Double(day/7.0))).intValue();
         
		usr = settings.getString("LifeGuideUser", "");
		intervention = settings.getString("LifeGuideInterventionId", "");
        
		if(settings.getBoolean("SensorsOn", false))
			psl = new PageSensorLogger(this);
		
		pl= new PageLogger(this);
		
		class AsyncLogAndRetrieve extends AsyncTask{

			@Override
			protected Object doInBackground(Object... params) {
				//usage Logging
				try{
					/*editor.putString("usageLog", settings.getString("usageLog", "")+params[0].getClass().getSimpleName()+" "+new Date()+", ");
		        	editor.commit();
		        	if(!usr.equals("")&&!intervention.equals(""))
		        		lgc.postVar(intervention, usr, "user", "appUsageLog", settings.getString("usageLog", ""), settings.getString("authkey",""));
		        	else
		        		Log.i("POWeR Tracker: ", "Log fail usr: "+usr+" int: "+intervention);
					*/
					pl.makeLog();
		        
		        	//Sensor Logging
		        	if(settings.getBoolean("SensorsOn", false)){
		    			psl.makeLog();
		        	}
		        	
		        	String planValue = lgc.getVar(intervention, usr, "user", "PAplan",settings.getString("authkey",""));
	        		
        			if(planValue!=null){
        				editor.putString("PAplan", planValue);
        				editor.commit();
        				activityPlan =planValue;
        			}
				}
				catch(PowerTrackerInvalidAuthKeyException e){
					invalidKey();
				}
				return null;
			}
		};
		
		new AsyncLogAndRetrieve().execute(this);
		
        svmain = new ScrollView(this);
        
        llmain = new LinearLayout(this);
        llmain.setOrientation(llmain.VERTICAL);
        
        TextView title = new TextView(this);
        title.setText("Daily Goal Update");
        title.setTextSize(20);
        llmain.addView(title);
        
        TextView subtitle = new TextView(this);
        subtitle.setText("How are your POWeR goals going today?");
        subtitle.setTextSize(19);
        llmain.addView(subtitle);
        
        //TimeCheck
        String lastUpdate=settings.getString("lastDailyUpdate", "");
    	Date tempDate = new Date();
    	String now = tempDate.getDate()+"-"+tempDate.getMonth()+"-"+tempDate.getYear();
    	
    	//Use NI to check for a connection
    	ConnectivityManager cm = (ConnectivityManager)PowerTrackerApplication.getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo ni = cm.getActiveNetworkInfo();
    	
    	//check to see if an update was made yet today. Setting OR boolean to true overides this check.
    	if((!lastUpdate.equals(now)||!settings.getBoolean("DailyUpdateInhibitorOn", true))&&ni!=null){
    		
    		class AsyncGetGoals extends AsyncTask{
    			LinearLayout llasync;
    			@Override
    			protected Object doInBackground(Object... params) {
    				Log.i("POWeR Tracker Special: ", "Async begin");
    				llasync=new LinearLayout((Activity)params[0]);
    				llasync.setOrientation(llmain.VERTICAL);
    				try{
    					for(int i=1;i<8;i++){
    						String goalvar = "currentgoal"+i;
    						if(i>3)
    							goalvar="currentpagoal"+(i-3);
    						if(i>6)
    							goalvar="currentsteps";
    	        			String tempgoal = lgc.getVar(intervention, usr, "user", goalvar,settings.getString("authkey",""));
    	        			if(i>6)
    							tempgoal=tempgoal+=" steps";
    	        			if(tempgoal!=null&&(i<4||(i<7&&activityPlan.equals("mix"))||(i==7&&activityPlan.equals("walk")))){        	
    	        				TextView g1 = new TextView((Activity)params[0]);
    	        				goal[i-1]=tempgoal;
    	        				g1.setText(goal[i-1]);
    	        				g1.setTextSize(18);
    	        				llasync.addView(g1);
    	        				RadioGroup g1_rg = new RadioGroup((Activity)params[0]);
    	        		
    	        				RadioButton g1_o1 = new RadioButton((Activity)params[0]);
    	        				g1_o1.setText("It's going really well");
    	        				g1_o1.setTag(new Integer(i));
    	        				g1_o1.setOnClickListener(new View.OnClickListener(){
    	         					@Override
    	         					public void onClick(View v) {
    	         						radioButtonClicked((Integer)v.getTag(),3);				
    	         					}
    	                		});
    	        				g1_rg.addView(g1_o1);
    	        		
    	        				RadioButton g1_o2 = new RadioButton((Activity)params[0]);
    	        				g1_o2.setText("It's going OK but I need to work on this one more");
    	        				g1_o2.setTag(new Integer(i));
    	        				g1_o2.setOnClickListener(new View.OnClickListener(){
    	         					@Override
    	         					public void onClick(View v) {
    	         						radioButtonClicked((Integer)v.getTag(),2);				
    	         					}
    	                		});
    	        				g1_rg.addView(g1_o2);
    	        		
    	        				RadioButton g1_o3 = new RadioButton((Activity)params[0]);
    	        				g1_o3.setText("I'm struggling");
    	        				g1_rg.addView(g1_o3);
    	        				g1_o3.setTag(new Integer(i));
    	        				g1_o3.setOnClickListener(new View.OnClickListener(){
    	         					@Override
    	         					public void onClick(View v) {
    	         						radioButtonClicked((Integer)v.getTag(),1);				
    	         					}
    	                		});
    	        				llasync.addView(g1_rg);
    	        			
    	        				goalcount++;
    	        			}
    	        		}
    				}
					catch(PowerTrackerInvalidAuthKeyException e){
						invalidKey();
					}
    	        	
    	              
    	        	Button submit = new Button((Activity)params[0]);
    	        	submit.setText("Save");
    	        	submit.setOnClickListener(new View.OnClickListener(){
    					@Override
    					public void onClick(View v) {
    						submit(v);				
    					}
    	        	});
    	        
    	        	llasync.addView(submit);
    				return null;
    			}
    			protected void onPostExecute(Object result) {
    				Log.i("POWeR Tracker Special: ", "Async Done");
    				asyncLayoutComplete(llasync);
    			}
    		};
    		new AsyncGetGoals().execute(this);
    		Log.i("POWeR Tracker Special: ", "Execute Async");
    	}
    	
    	//If they've already done an update today
    	else if(lastUpdate.equals(now)){
    		TextView repeatWarning = new TextView(this);
    		repeatWarning.setText(getResources().getString(R.string.multipleUpdateInhibitorError));
    		repeatWarning.setTextSize(12);
            llmain.addView(repeatWarning);
    		
    		Button backToMenuButton = new Button(this);
    		backToMenuButton.setText("Save Update");
    		backToMenuButton.setOnClickListener(new View.OnClickListener(){
    			@Override
    			public void onClick(View v) {
    				backToMenu();				
    			}
            });
            
            llmain.addView(backToMenuButton);
            svmain.addView(llmain);
    		
    	}
    	
    	//if they have no net connection
    	else if(ni==null){
    		TextView repeatWarning = new TextView(this);
    		repeatWarning.setText(getResources().getString(R.string.offlineUpdateError));
    		repeatWarning.setTextSize(12);
            llmain.addView(repeatWarning);
    		
    		Button backToMenuButton = new Button(this);
    		backToMenuButton.setText("Save Update");
    		backToMenuButton.setOnClickListener(new View.OnClickListener(){
    			@Override
    			public void onClick(View v) {
    				backToMenu();				
    			}
            });
            
            llmain.addView(backToMenuButton);
            svmain.addView(llmain);
    		
    	}
 
        setContentView(svmain);

    }
	
	@Override
    protected void onPause() {
        super.onPause();
        if(psl!=null)
        	psl.stopLocationSensing();
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        if(psl!=null)
        	psl.resumeLocationSensing();
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        	
    	switch (item.getItemId()) {
            case android.R.id.home:
                // app icon in action bar clicked; go home
                goHome();
                return true;
            case R.id.home:
                // app icon in options clicked; go home
            	goHome();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.o_menu, menu);
        return true;
    }
    
    public void goHome(){
    	Intent intent = new Intent(this, PowerTrackerActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }
    
    public void submit(View v){
    	
    	Log.i("POWeR Tracker: ", "Daily Goal Update Submit");
    	
      	boolean updateValidate = true;
      	int totalUpdates=0;
    	for(int i =0; i<7; i++){
    		if(update[i]!=0)
    			totalUpdates++;
    	}
    	if(totalUpdates!=goalcount)
    		updateValidate=false;
    	
    	if(updateValidate){
    		Intent myIntent = new Intent().setClass(this, DailyGoalUpdateFeedbackActivity.class);
    		
    		for(int i =0; i<7; i++){
        		if(update[i]!=0){
        			       		        		
        			myIntent.putExtra("dailygoalupdate"+(i+1), update[i]+"");
        			myIntent.putExtra("currentgoal"+(i+1), goal[i]);
        		}
        	}
    		
    		int weeklystars = new Integer(settings.getString("week"+week+"stars", "0"));
			weeklystars++;
			editor.putString("week"+week+"stars", ""+weeklystars);
			editor.commit();
    		
    		class AsyncPostUpdate extends AsyncTask{
    			@Override
    			protected Object doInBackground(Object... params) {
    				try{
    					for(int i =0; i<7; i++){
    	        			if(update[i]!=0){
    	        				lgc.postVar(intervention, usr, "user", "dailygoalupdate-"+(i+1), update[i]+"",settings.getString("authkey",""));
    	        				lgc.postVar(intervention, usr, "user", "dailygoalupdate-"+(i+1)+"-"+day, update[i]+"",settings.getString("authkey",""));
    	        			}
    					}
    				}
    				catch(PowerTrackerInvalidAuthKeyException e){
    					invalidKey();
    				}
    				 				
    				return null;
    			}
    		};
    		new AsyncPostUpdate().execute(this);
    		
    		
        	startActivityForResult(myIntent, 0);

        	//Update time last update was submitted.
        	
        	Date tempDate = new Date();
        	editor.putString("lastDailyUpdate", tempDate.getDate()+"-"+tempDate.getMonth()+"-"+tempDate.getYear());
            editor.commit();
    	}
    	else{
    		 Toast.makeText(this, getResources().getString(R.string.updateValidationError), Toast.LENGTH_SHORT).show();
    	}
    	
    }
    
    public void backToMenu(){
    	
    	Intent myIntent = new Intent().setClass(this, PowerTrackerActivity.class);
    	startActivityForResult(myIntent, 0);
	
    }
    
    public void radioButtonClicked(int goal, int val){
    	Log.i("POWeR Tracker: ", "Daily Goal Update Set "+goal+" to "+val);
    	update[goal-1]=val;
    }
    
    public void asyncLayoutComplete(LinearLayout asll){
    	llmain.addView(asll);
    	svmain.addView(llmain); 
    	//Log.i("POWeR Tracker Special: ", "Update Async Complete!");
    }
    
    public void invalidKey(){
    	DialogFragment dialog = new LoginDialog();
		Bundle errorBundle = new Bundle();
	    errorBundle.putString("error", "Your Authentication Key is invalid, expired, or is missing. Please Log In.");
	    dialog.setArguments(errorBundle);
	    //dialog.show(this.getFragmentManager(), "LoginDialog");
	    dialog.show(this.getSupportFragmentManager(), "LoginDialog");
	}
    
  	@Override
	public void onLoginDialogPositiveClick() {
		// TODO Auto-generated method stub
  		Log.i("POWeR Tracker Special: ","Clicked OK");
  		finish();
  		startActivity(getIntent());
	}


	@Override
	public void onLoginDialogNegativeClick() {
		// TODO Auto-generated method stub
		Log.i("POWeR Tracker Special: ","Clicked Cancel");
		goHome();
	}

}